package pro.lingwu.rainbowmall.controller

import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.thymeleaf.context.WebContext
import pro.lingwu.rainbowmall.dto.User
import pro.lingwu.rainbowmall.service.UserService
import pro.lingwu.rainbowmall.util.KeyConstant
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.validation.Valid

/**
 * 用户信息的控制器
 *
 * @author lingwu
 */
@RestController
@RequestMapping("/user")
class UserController {

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var keys: KeyConstant

    /**
     * 获取邮箱验证码的接口
     *
     */
    @GetMapping("/verification-code")
    fun getVerificationCode(mail: String,
                            servletRequest: HttpServletRequest,
                            servletResponse: HttpServletResponse): ResponseEntity<*>? {
        val context = WebContext(servletRequest, servletResponse, servletRequest.servletContext)
        userService.sendVerification(context, mail)

        return ResponseEntity.ok("ok")
    }

    /**
     * 用户注册接口
     * 接口参数已验证
     * 注意前端保持一致
     * 请注意验证码要一定填数字
     * 验证用户（通过validation）-> 验证邮箱得到的验证码（异常） -> 存储头像（异常） -> 使用头像id存储到用户中
     */
    @ApiOperation(value = "用户注册", httpMethod = "POST")
    @PostMapping
    fun userRegister(@Valid user: User,
                     photo: MultipartFile,
                     @RequestParam(name = "code", required = true) verificationCode: String): ResponseEntity<*>? {

        userService.verifyCode(user.mail, verificationCode)

        userService.register(user, photo)

        return ResponseEntity.ok("ok")
    }


    /**
     * 用户登录接口
     * 传入账号密码即可
     * 处理Cookies -> 根据账号密码获取用户信息 -> 返回用户信息
     */
    @GetMapping
    fun userLogin(user: User, remember: Boolean,request: HttpServletRequest, response: HttpServletResponse)
    : ResponseEntity<*>{

        val sessionsList = request.cookies?.filter { cookie -> cookie.name == keys.rememberKey }
        var key: String? = null
        if (sessionsList != null && sessionsList.isNotEmpty()) {
            key = sessionsList[0].value
        }
        val account = userService.verifyCookies(key)
        var res: User? = null
        res = if (account != null) userService.verifyUser(account, null, autoLogin = true)
        else userService.verifyUser(user.account, user.password, autoLogin = false)

        // 记住用户
        if (remember){
            val sessionKey = userService.rememberUser(user)
            if (sessionKey != null){
                val cookie = Cookie(keys.rememberKey, sessionKey)
                cookie.maxAge = (keys.rememberTime*24*3600).toInt()
                response.addCookie(cookie)
            }
        }

        return ResponseEntity.ok(res)
    }

}